<template>
	<view class="address-list" @tap.stop="">
		<view class="address-title">
			<text>请选择打卡地点</text>
			<button class="btn" size="mini" @tap="itemSeleted('done','')">确认选择</button>
		</view>
		<view class="address-list" v-if="isNull(addressList)">
			<text style="display: inline-block;width:100%;text-align: center;color: #999;margin-top:100px;">地址列表加载中…</text>
		</view>
		<scroll-view class="address-list" scroll-y>
			<view class="item"
				v-for="item in addressList" 
				:key="item.id" 
				@tap="itemSeleted('select',item)" >
				<text :style="{color: item.selected?'rgb(255,211,3)':''}">{{item.title}}</text>
				<text class="tip">{{item.address}}</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { onMounted, ref } from "vue"
import request from "../../util/request.js"
import util from "../../util/util.js"
	export default {
		name:"adrlist",
		props: ['coords'],
		setup(props,ctx) {
			onMounted(()=>{
				getAddress(props.coords)
			})
			let addressList = ref([])
			async function getAddress(mark) {
				let g = {}
				g.lat = mark.lat
				g.lng = mark.lng
				let _markcoord = uni.getStorageSync('markcoord')
				if (g.lat == _markcoord.lat && g.lng == _markcoord.lng) {
					addressList.value = uni.getStorageSync('address')
					return
				}
				let r = await request.getAddress(g)
				if (r.status == 0) {
					if (r.result) {
						addressList.value = r.result.pois || []
						uni.setStorageSync('address',addressList.value)
						uni.setStorageSync('markcoord',g)
					}
				}
			}
			
			// 选点及确认选择
			function itemSeleted(f,data = {}) {
				let _adrList = addressList.value
				for (let i in _adrList) {
					if (f == 'done') {
						if (_adrList[i].selected) data = _adrList[i]
					}
					if (f == 'select') {
						_adrList[i].selected = false
						if (_adrList[i].id == data.id) {
							_adrList[i].selected = true
						}
					}
				}
				addressList.value = _adrList
				if (util.isNull(data)) {
					uni.showToast({
						title: '请选择打卡地点',
						icon: 'none'
					})
					return
				}

				data.flag = f
				ctx.emit('action', data)
			}
			
			function isNull(v) {
				return util.isNull(v)
			}
			
			return {
				addressList, itemSeleted, isNull
			}
		}
	}
</script>

<style lang="scss">
	.address-list{
		display: block;
		width: 100%;height: 100%;
		max-height: calc(90vh);
		padding: 0;
		background-color: #fff;
		.address-title{
			@extend %flex-view;
			width: 100%;height: 45px;
			flex-direction: row;
			justify-content: space-between;
			padding: 0 15px;
			background-color: $color-main;
			.btn{
				background-color: $color-blue;
				color: #fff;
				margin: 0;
			}
		}
		.address-list{
			display: block;
			width: 100%;height:calc(100% - 45px);
			.item{
				@extend %flex-view;
				align-items: flex-start;
				padding: 12px 20px;
				border-bottom: 1px solid #eee;
				.tip{
					font-size: 14px;
					color: #999;
					margin-top: 3px;
				}
			}
		}
	}
</style>